<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"
import { exportToExcel } from '@/utils/exportUtils'

defineOptions({ name: '佣金明细' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  goods_all:[],
  data_ini:{
    type: [],
    category_id:[],
    cdp_type:[]
  },
  select_customers:[],
  search_loading:false,
  is_check_data:[{id:1,name:"已通过"},{id:0,name:"待审核"}],
  total_price:0
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '佣金明细',
  initForm: {},
  doCreate: api.createUserYongjin,
  doUpdate: api.updateUserYongjin,
  doDelete: api.deleteUserYongjin,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
})

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getUserYongjinList({
      ...queryItems.value,
      is_export:1,
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      ID: item.id,
      渠道姓名: item.yeji_uname,
      佣金类型: item.yeji_type_name,
      订单号: item.xf_id,
      客户姓名: item.nme,
      项目名: item.xmnme,
      项目金额: item.xm_price,
      佣金基数: item.price,
      消费时间: item.xf_dte,
      业绩提成: item.yeji_price,
      生成时间: item.insert_dte,
      核对状态: item.chk === 1 ? '已审核' : '待审核',
      核对时间: item.chk_dte,
      发放状态: item.give === 1 ? '已支付' : '未支付',
      发放时间: item.give_dte
    }))

    // 导出Excel
    exportToExcel(exportData, `佣金明细_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}


const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 50,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '渠道姓名',
    key: 'yeji_uname',
    width: 120,
    align: 'center',
    fixed: 'left',
    render(row) {

      return h(NFlex, {justify: "center",
        align: "center"},
        [h(NButton, {
          size: "small",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.yeji_uname)
        })]
      )

    },
  },
  {
    title: '佣金类型',
    key: 'yeji_type_name',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '订单号',
    key: 'xf_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '客户姓名',
    key: 'nme',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '项目名',
    key: 'xmnme',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '项目金额',
    key: 'xm_price',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  }
  // ,{
  //   title: '实际支付',
  //   key: 'price',
  //   width: 100,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // }
  ,{
    title: '佣金基数',
    key: 'price',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '消费时间',
    key: 'xf_dte',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  }
  ,
    {
    title: '业绩提成',
    key: 'yeji_price',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '生成时间',
    key: 'insert_dte',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '核对状态',
    key: 'chk',
    width:100,
    align: 'center',
    render(row) {
      if(row.chk === 1){
        return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.chk_name })
      }else{
        return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.chk_name })
      }

    },
  },
    {
    title: '核对时间',
    key: 'chk_dte',
    width:120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '发放状态',
    key: 'give',
    width:100,
    align: 'center',
    render(row) {
      if(row.give === 1){
        return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => "已支付" })
      }else{
        return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => "未支付" })
      }

    },
  },
    {
    title: '发放时间',
    key: 'give_dte',
    width:120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 270,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: row.chk===1?'error':'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_check(row)
              },
            },
            {
              default: () => row.chk===1?'已审核':'待审核',
              icon: renderIcon(row.chk===1?'material-symbols:check':'material-symbols:acute-outline', { size: 16 }),
            }
          ),
          []
        ),
          withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: row.give===1?'error':'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_give(row)
              },
            },
            {
              default: () => row.give===1?'已支付':'待支付',
              icon: renderIcon(row.give===1?'material-symbols:check':'material-symbols:acute-outline', { size: 16 }),
            }
          ),
          []
        ),
          withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;width:30px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                    style: 'margin-right: 0px;width:30px;',
                  },
                  {

                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]



const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}


function on_check(row){
  if(row.chk===1){
    message.success('已经完成了审核');
  }else{
    on_save(row)
  }
}

function on_give(row){
  if(row.give===1){
    message.success('已经完成了发放');
  }else{
    on_save1(row)
  }
}

function on_save(row){
  row.chk = 1
  row.chk_dte = new Date().toISOString().split('T')[0]
  api.updateUserYongjin(row).then((res) => {
    $table.value?.handleSearch()
    message.success('更新成功');
  })
}

function on_save1(row){
  if(row.chk===0){
    message.error('请先审核');
    return
  }
  row.give = 1
  row.give_dte = new Date().toISOString().split('T')[0]
  api.updateUserYongjin(row).then((res) => {
    $table.value?.handleSearch()
    message.success('更新成功');
  })
}

function on_edit(row){
  handleEdit(row)
}


function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}
const total_price = computed(() => {
  const tableData = $table.value?.tableData || []; // 假设表格数据存储在tableData中
  if (tableData.length > 0) {
    return Number(tableData[0]?.total_price || 0); // 返回一条数据的值，确保为数字
  }
  return 0; // 默认值
});

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getUserYongjinList"
          :scroll-x="2000"
          :maxheight="420"
        >
          <template #queryBar>
            <QueryBarItem label="渠道姓名" :label-width="80">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="输入员工姓名"
                @keypress.enter="$table.value?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="审核状态" :label-width="80">
              <NSelect
                v-model:value="queryItems.chk"
                style="width: 200px;"
                :options="data.is_check_data"
                clearable
                label-field="name"
                    value-field="id"
                placeholder="选择审核状态"
              />
            </QueryBarItem>
            <QueryBarItem label="创建时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

            <QueryBarItem label="订单编号" :label-width="80">
              <NInput
                v-model:value="queryItems.xf_id"
                clearable
                type="text"
                placeholder="订单编号"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem style="line-height: 35px;color: red" label="总业绩提成:" :label-width="80">
              {{total_price}}
            </QueryBarItem>

          </template>

        </CrudTable>
        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
                <NFormItem label="业绩金额" path="yeji_price">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.yeji_price" placeholder="请输入价格" />
                </NFormItem>
                <NFormItem label="备注" path="remark">
                  <n-input  style="width: 100%"   v-model:value="modalForm.remark" placeholder="备注" />
                </NFormItem>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
